package com.easyattendance.services;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.easyattendance.model.Class;
import com.easyattendance.model.Parent;
import com.easyattendance.model.Student;
import com.easyattendance.model.StudentElective;
import com.easyattendance.util.HibernateUtil;

public class AddStudentService {

	/* Method to CREATE a student in the database */
	   public synchronized boolean addStudent(Student student){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	        	 session.save(student);
	           	 tx.commit();
	           	result=true; 

	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return result;
	   }
	   
	   /* Method to UPDATE a student in the database */
	   public synchronized boolean updateStudent(Student student){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	        	 session.update(student);
	           	 tx.commit();
	           	result=true; 

	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return result;
	   }
	   
	   public int getStudentIdValue()
	   {
		   	Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        int value=0;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	            SQLQuery query = session.createSQLQuery("select MAX(stud_id) from tbl_student");
	           
	            if(query.uniqueResult()!=null)
	            {
	            	String stud_id=(String) query.uniqueResult();
	            	//String section_counter=section_id.substring(7);
	            	value = Integer.parseInt(stud_id)+1;
	            }
	            else
	            	value=1;
	            
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
		   
		   return value;
	   }
	   
	   /* Method to DELETE an student from the records */
	   public synchronized boolean deleteStudent(String studentId){
		   Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean flag = false;
	      try{
	         tx = session.beginTransaction();
	         Student student = (Student) session.createQuery("FROM Student where stud_id='"+studentId+"'").uniqueResult();
	         
	         List<Parent> parentList = session.createQuery("FROM Parent where parent_id='"+student.getParent().getParent_id()+"'").list();
	         
	         if(parentList.size() == 1) {
	        	 session.delete(student.getParent());
	         }
	         session.delete(student);
	         
	         tx.commit();
	         flag = true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return flag;
	   }
	   
	   /* Method to CREATE a student_elective data in the database */
	   public synchronized boolean addStudentElective(StudentElective studentElective){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	        	 session.save(studentElective);
	           	 tx.commit();
	           	result=true; 

	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return result;
	   }
	   
	   public boolean ifStudentElectiveAlreadyExists(StudentElective studentElective) {
		   boolean flag = false;
			 
			 Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List students = null;
		      try{
		         tx = session.beginTransaction();
		         students = session.createQuery("FROM StudentElective").list(); 
		         for (Iterator iterator = students.iterator(); iterator.hasNext();){
		        	StudentElective student = (StudentElective) iterator.next(); 
		            if(student.equals(studentElective)) {
		            	System.out.println("Student Elective already exists");
		            	flag = true;
		            	break;
		            }
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
			 
			 return flag;
		}
	   
	   /*public boolean ifAlreadyExists(int studentId) {
			 boolean flag = getUserByUserId(studentId);
			 
			 return flag;
			 if(stud!=null && stud.getName().equals(studName) ){
				 return false;
			 }else{
				 return true;
			 }
		}*/
	   
	   public boolean ifAlreadyExists(Student newStudent) {
			 boolean flag = false;
			 
			 Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List students = null;
		      try{
		         tx = session.beginTransaction();
		         students = session.createQuery("FROM Student").list(); 
		         for (Iterator iterator = students.iterator(); iterator.hasNext();){
		        	Student student = (Student) iterator.next(); 
		            if(student.getStud_roll_no()==newStudent.getStud_roll_no()) {
		            	System.out.println("Student already exists");
		            	flag = true;
		            	break;
		            }
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
			 
			 return flag;
			 /*if(stud!=null && stud.getName().equals(studName) ){
				 return false;
			 }else{
				 return true;
			 }*/
		}
		public boolean getUserByUserId(int studentRollNo) {
			 Session session = HibernateUtil.openSession();
			 Transaction tx = null;
			 //Teacher teacher = null;
			 Query query=null;
			 boolean flag = false;
			 try {
				 tx = session.getTransaction();
				 tx.begin();
				// tx = session.beginTransaction();
				 query = session.createQuery("from Student where stud_roll_no="+studentRollNo);
				 List list = query.list();
				 			 
				 if (list.isEmpty()) {
					 flag = false;
				 }
				 else {
					 flag = true;
				 }
				 if (!tx.wasCommitted()) {
					 tx.commit();
				 }
					 
			 } catch (Exception e) {
				 if (tx != null) {
					 tx.rollback();
				 }
				 e.printStackTrace();
			 } finally {
				 session.close();
			 }
			return flag;
		}
		
		/* Get student by student roll no */
		public Student getStudentByStudentRollNo(String studRollNo) {
	        Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        Student user = null;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	            Query query = session.createQuery("from Student where stud_roll_no='"+studRollNo+"'");  
	            user = (Student)query.uniqueResult();
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
	        return user;
	    }
		
		/* Get student by studentID */
		public Student getStudentByStudentId(String studId) {
	        Session session = HibernateUtil.openSession();
	        Transaction tx = null;
	        Student user = null;
	        try {
	            tx = session.getTransaction();
	            tx.begin();
	            Query query = session.createQuery("from Student where stud_id='"+studId+"'");
	            user = (Student)query.uniqueResult();
	            tx.commit();
	        } catch (Exception e) {
	            if (tx != null) {
	                tx.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.close();
	        }
	        return user;
	    }
	   
		/* Method to  READ all the Student values */
		   public ArrayList<Student> listStudents( ) {
			  Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List<Student> students = null;
		      try{
		         tx = session.beginTransaction();
		         students = session.createQuery("FROM Student").list(); 
		         for (Iterator iterator = students.iterator(); iterator.hasNext();){
		        	Student student = (Student) iterator.next(); 
		            System.out.print("Student Name: " +student.getStud_fname()); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return (ArrayList<Student>) students;
		   }
		   
		   /* Method to  READ all the Student values for particular section and class */
		   public ArrayList<Student> getStudentList(String sectionId,String classId) {
				Session session = HibernateUtil.openSession();
				Transaction tx = null;
				ArrayList<Student> studentList=new ArrayList<Student>();
				//Student[] studentList = new Student[100];

				try {
					tx = session.beginTransaction();
					studentList = (ArrayList<Student>) session.createQuery("FROM Student WHERE section_id='" + sectionId + "' AND class_id='"+classId+"'").list();
					
					/*for(Iterator iterator =studList.iterator(); iterator.hasNext();)
					{
						 Student stud=(Student)iterator.next();
						 String studid=stud.getStud_id();
						 String studnm=stud.getStud_fname();
						 
						 //studentList.add(new Student(studid,studnm));
						 studentList.add(stud);
					}*/
					
					tx.commit();

				} catch (HibernateException e) {
					if (tx != null)
						tx.rollback();
					e.printStackTrace();
				} finally {
					session.close();
				}
				return studentList;
			}
	   
}
